<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <ul>
        <li><a href="#/home">首页</a></li>
        <li><a href="#/about">关于</a></li>
    </ul>

    <!-- 当 url 变更后，展示对应的代码片段 -->
    <div id="root"></div>

    <script>
        const routes = [
            {
                path: '/home',
                component: () => {
                    return '<h1>首页页面</h1>'
                }
            },
            {
                path: '/about',
                component: () => {
                    return '<h1>关于页面</h1>'
                }
            }
        ]

        //要知道 url 变更了
        window.addEventListener('hashchange', () => {
            console.log(location.hash)
            renderView(location.hash)
        })
        function renderView(url) {  // #/home
            const index = routes.findIndex(item => {
                return ('#' + item.path) === url
            })
            let routerView = document.getElementById('root')
            routerView.innerHTML = routes[index].component()
        }
        
        window.addEventListener('DOMContentLoaded', () => {
            renderView(location.hash)
        })

    </script>

</body>

</html>